package marketdepth;

import order.OrderBuy;
import order.OrderSale;
import transaction.Transaction;

import java.util.TreeSet;

public class SingleMarketDepth {

    private final TreeSet<OrderBuy> asks = new TreeSet();
    private final TreeSet<OrderSale> bids = new TreeSet();
    private final Object lockAsks = new Object();
    private final Object lockBids = new Object();

    public Transaction fillOrders() {
        if ((asks.isEmpty())||(bids.isEmpty())) {
            return null;
        }
        synchronized (lockAsks) {
            synchronized (lockBids) {
                if ((!asks.isEmpty())&&(!bids.isEmpty())&&
                        (bids.first().getPrice() <= asks.last().getPrice())) {
                    return new Transaction(asks.pollLast(), bids.pollFirst());
                }
            }
        }
        return null;
    }

    public void addOrderSale(OrderSale orderSale) {
        synchronized (lockBids) {
            bids.add(orderSale);
        }
    }

    public void addOrderBuy(OrderBuy orderBuy) {
        synchronized (lockAsks) {
            asks.add(orderBuy);
        }
    }
}
